package com.wk.aidldemo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.view.View;
import android.widget.TextView;

import com.wk.aidldemo.tool.WkLogTool;
import com.wk.aidldemo.tool.tasktool.HeartBeatTask;
import com.wk.aidldemo.tool.tasktool.WkHeartBeatTool;
import com.wk.aidldemo.wkAidl.Book;
import com.wk.aidldemo.wkAidl.IBookManager;
import com.wk.aidldemo.wkAidl.IOnNewBookArrivedListener;

import java.util.List;

public class MainActivity extends Activity {
    private TextView mTvBookList;
    private IBookManager mRemoteBookManager;
    private WkHeartBeatTool wkHeartBeatTool = new WkHeartBeatTool();
    private Context context ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context= this ;
        initView() ;
    }


    private void initView(){
        mTvBookList =  findViewById(R.id.main_tv_book_list);
        findViewById(R.id.bindService).setOnClickListener(onClickListener);
        findViewById(R.id.exitClient).setOnClickListener(onClickListener);
        findViewById(R.id.addBook).setOnClickListener(onClickListener);
        findViewById(R.id.getBookInfo).setOnClickListener(onClickListener);
    }


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id=view.getId();
            if(id==R.id.bindService){
                Intent intent=new Intent();
                intent.setAction("com.remoteService.test"); //用来识别service的标记
                intent.setPackage("com.wk.iadlservice"); // 服务所在的应用id
                bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
            }


            else if(id==R.id.exitClient){
                ( (Activity) context).finish();
                System.exit(0);
            }

            else if(id==R.id.addBook){
                if(mRemoteBookManager==null){
                    return;
                }

                try {
                    Book newBook = new Book( "book_"+System.currentTimeMillis());
                    mRemoteBookManager.addBook(newBook);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }

            else if (id==R.id.getBookInfo){
                WkLogTool.showLog("R.id.getBookInfo"  );
                wkHeartBeatTool.startDelayedAction(new HeartBeatTask() {
                    @Override
                    public void run() {
                        String  info=  getBooksInfo();
                        showMsg("getBookInfo=\r\n"+ info);
                        boolean isInMainThread= Looper.getMainLooper()== Looper.myLooper() ;
                        WkLogTool.showLog("isMain=="+isInMainThread);
                    }
                } ,0);

            }

        }
    };

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override public void onServiceConnected(ComponentName name, IBinder service) {
            try {
                IBookManager bookManager = IBookManager.Stub.asInterface(service);
                mRemoteBookManager = bookManager;
                bookManager.registerListener(mOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override public void onServiceDisconnected(ComponentName name) {
            mRemoteBookManager = null;
        }
    };

    private IOnNewBookArrivedListener mOnNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() {
        @Override public void onNewBookArrived(final Book newBook)   {

            showMsg("添加完毕== \r\n"+ newBook.toString());

        }
    };



    @Override
    protected void onDestroy() {
        if (mRemoteBookManager != null && mRemoteBookManager.asBinder().isBinderAlive()) {
            try {
                mRemoteBookManager.unregisterListener(mOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        try {
            unbindService(mConnection);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }


    private String getBooksInfo()  {
        StringBuilder sb = new StringBuilder( ) ;
        try {
            List<Book> list  = mRemoteBookManager.getBookList();
            for(Book book: list){
                sb.append(book.toString()).append("\r\n") ;
            }
        } catch (RemoteException e) {
            sb.append(e.getCause()) ;
            e.printStackTrace();
        }
        return sb.toString() ;
    }



    private void showMsg(final String msg){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvBookList.setText(msg);
            }
        });

    }

 }//

